﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using DevelopersToolbox;

namespace XmlTools {
    public partial class XPathControl : UserControl, IExecutableTool {
        public XPathControl() {
            InitializeComponent();
        }

        private void _evaluate_Click(object sender, EventArgs e) {
            Execute();
        }

        private void AddXPathToList() {
            string text = _xpath.Text;
            _xpath.Items.Remove(text);
            _xpath.Items.Insert(0, text);
            _xpath.Text = text;
        }

        public void Execute() {
            try {
                XmlDocument doc = _sourceSelect.GetDataAsXml();
                XmlNodeList nodes = doc.SelectNodes(_xpath.Text);
                StringBuilder result = new StringBuilder();
                int index = 1;
                int count = nodes.Count;
                foreach (XmlNode node in nodes) {
                    result.AppendLine(string.Format("- ({0}/{1}) -----------------------------------", index, count));
                    result.AppendLine(node.OuterXml);
                    index++;
                }
                _results.Text = result.ToString();

                _sourceSelect.AddTextToDropDown();
                AddXPathToList();
            }
            catch (Exception ex) {
                _results.Text = ex.ToString();
            }
        }
    }
}